using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using MySql.Data.MySqlClient;
using Publicuse.Autofac;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Interface.Extend;
using Publicuse.Util;
using ServiceStack;
using SqlSugar;

namespace Publicuse.Appication
{
  /// <summary>
  /// 业务基类操作
  /// </summary>
  public class BaesApplication
  {
    private List<City> cities = new List<City>();

    public readonly IAutofaceInstance autofaceInstance;

    public readonly IMySqlSugarService mySqlSugar;

    public readonly IWebHostEnvironment webHost;

    public readonly IBaseServiceExt baseServiceExt;

    public BaesApplication(ServiceContainer serviceContainer)
    {
      this.autofaceInstance = serviceContainer.autofaceInstance;
      this.mySqlSugar = serviceContainer.mySqlSugar;
      this.webHost = serviceContainer.webHost;
      this.baseServiceExt = serviceContainer.baseServiceExt;
      var table = TableAtributeUtil.GetTable<City>();
      var sql = $"select * from {table}";
      this.mySqlSugar.Work(
        out var msg,
        db =>
        {
          this.cities = db.SqlQueryable<City>(sql).ToList();
        },
        false
      );
    }

    /// <summary>
    /// 查询信息列表有缓存查询缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetListToCache<T>(CommonQuery query)
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var loginUserCode = HttpContextExtendBase.GetLoginCode();
        result = autofaceInstance.DoWork(
          BusinessType.querycache,
          BusinessActionType.query,
          query,
          "查询缓存",
          BusinessLogType.writeLogToFile,
          o =>
          {
            string msg = string.Empty;
            List<T> list = new List<T>();
            long totalCount = 0;
            this.mySqlSugar.GetPageListByProc<T>(query, out msg, out list, out totalCount);
            if (string.IsNullOrEmpty(msg))
            {
              result.count = totalCount;
              result.data = list;
            }
            else
            {
              result.msg = msg;
            }
            return result;
          },
          null,
          ref result
        );
        return result;
      });
    }

    /// <summary>
    /// 获取信息列表
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <param name="export"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetList<T>(
      CommonQuery query,
      bool export = false,
      Action<List<T>, long> action = null
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        string msg = string.Empty;
        List<T> list = new List<T>();
        long totalCount = 0;
        var key = TableAtributeUtil.GetTable<T>();
        var ishavehc = false;
        if (!string.IsNullOrEmpty(query.CacheKey))
        {
          if (QueryCacheUtil<T>.IsExists(key))
          {
            var data = QueryCacheUtil<T>.GetData(key);
            if (action != null)
            {
              if (data != null)
              {
                ishavehc = true;
                result.count = data.data.Count;
                action.Invoke(data.data, totalCount);
              }
            }
            else
            {
              if (data != null)
              {
                ishavehc = true;
                result.count = data.data.Count;
                result.data = data.data;
                result.etTime = DateTime.Now;
                return result;
              }
            }
          }
        }
        if (!ishavehc)
        {
          this.mySqlSugar.GetPageListByProc<T>(query, out msg, out list, out totalCount);
          if (action != null)
            action.Invoke(list, totalCount);

          if (!string.IsNullOrEmpty(query.CacheKey))
          {
            QueryCache<T> cache = new QueryCache<T>() { data = list };
            QueryCacheUtil<T>.AddData(key, cache);
          }
          if (export)
          {
            ExportDataExport<List<T>>.GetExportCBLL.InitExportData(
              (ins) =>
              {
                List<T> all = new List<T>();
                query.pageSize = 100000;
                this.mySqlSugar.GetPageListByProc(query, out msg, out all, out totalCount);
                ins.AddExportData(query.exportName, all);
              }
            );
          }
          if (string.IsNullOrEmpty(msg))
          {
            result.count = totalCount;
            result.data = list;
          }
          else
          {
            if (msg.Contains("SQL syntax"))
            {
              result.msg = "查询错误！";
            }
            else
            {
              //result.msg =msg;
              result.msg = msg;
            }
          }

          var headers = HttpContextExtendBase.Current.Request.Headers;
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          var remoteIp =
            LogClass.GetIPAddress()
            + "|"
            + headers["X-Real-IP"].ToString()
            + "|"
            + headers["X-Forwarded-For"].ToString();
          if (string.Compare(remoteIp, "::1", true) == 0)
          {
            remoteIp = HttpContextExtendBase
              .Current.Connection.LocalIpAddress.MapToIPv4()
              ?.ToString();
          }
          if (remoteIp.Split(':').Length >= 3)
          {
            remoteIp = remoteIp.Split(':')[3];
          }
          if (!string.IsNullOrEmpty(remoteIp))
          {
            remoteIp = remoteIp.Replace("unknow", "").Replace("|", "");
          }
          var RemoteIpAddress = HttpContextExtendBase.Current.Connection.RemoteIpAddress;
          var ipaddress = string.Empty;
          var newripad = RemoteIpAddress.ToString();
          if (!string.IsNullOrEmpty(newripad))
          {
            if (string.Compare(newripad, "::1", true) != 0)
            {
              ipaddress = $"{remoteIp + "|" + RemoteIpAddress}";
            }
            else
            {
              ipaddress = remoteIp;
            }
          }
          else
          {
            ipaddress = remoteIp;
          }
          ipaddress = ipaddress.Replace("|::ffff:", "");
          var loginUserCode = HttpContextExtendBase.GetLoginCode();
          var LoginrName = HttpContextExtendBase.GetLoginrName();
          var lmodule = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
            query.businessType
          );
          var lcontent = $"用户：{loginUserCode}查询【】信息,具体参数：{JsonUtil.ToJson(query)}";
          Log log = new Log()
          {
            ipaddress = ipaddress,
            lmodule = lmodule,
            ltype = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
              BusinessActionType.query
            ),
            lrole = LoginrName,
            luser = loginUserCode,
            lsuccess = 1,
            status = 1,
            lcontent = lcontent
          };
          this.mySqlSugar.InserBackId(log, out msg);
        }
        result.etTime = DateTime.Now;
        result.timeconsuming = result.GetHS();
        return result;
      });
    }

    /// <summary>
    /// 获取列表信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="entity">查询对象</param>
    /// <param name="pageIndex">当前第几条</param>
    /// <param name="pageSize">显示多少条记录</param>
    /// <param name="funcOrderby">排序字段</param>
    /// <param name="isAsc">是否降序</param>
    /// <param name="func">额外查询条件处理拼接</param>
    /// <param name="action">额外结果处理拼接</param>
    /// <returns></returns>
    public async Task<CommonResult> GetListByExpression<T>(
      T entity,
      int pageIndex,
      int pageSize,
      Expression<Func<T, object>> funcOrderby,
      bool isAsc,
      Func<Expression<Func<T, bool>>, Expression<Func<T, bool>>> func = null,
      Action<List<T>> action = null
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        string msg = string.Empty;
        baseServiceExt.ExcuteCustom(
          db =>
          {
            var exp = entity.GetQueryExpression<T>(func, out msg);
            if (string.IsNullOrEmpty(msg))
            {
              List<T> list = new List<T>();
              int tottal = 0;
              list = db.Queryable<T>()
                .Where(exp)
                .OrderByIF(true, funcOrderby, isAsc ? OrderByType.Asc : OrderByType.Desc)
                .ToPageList(pageIndex, pageSize, ref tottal)
                .ToList();

              if (action != null)
              {
                action?.Invoke(list);
              }
              result.data = list;
              result.count = tottal;
            }
          },
          out msg
        );
        result.timeconsuming = result.GetHS();
        result.msg = msg;
        return result;
      });
    }

    public async Task<CommonResult> GetListByExpression<T>(
    T entity,
    int pageIndex,
    int pageSize,
    bool isAsc,
    string orderfile,
    Func<Expression<Func<T, bool>>, Expression<Func<T, bool>>> func = null,
    Action<List<T>> action = null
  )
    where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        string msg = string.Empty;
        baseServiceExt.ExcuteCustom(
          db =>
          {
            var exp = entity.GetQueryExpression<T>(func, out msg);
            if (string.IsNullOrEmpty(msg))
            {
              List<T> list = new List<T>();
              int tottal = 0;
              list = db.Queryable<T>()
                .Where(exp)
                .OrderByIF(isAsc, orderfile)
                .ToPageList(pageIndex, pageSize, ref tottal)
                .ToList();

              if (action != null)
              {
                action?.Invoke(list);
              }
              result.data = list;
              result.count = tottal;
            }
          },
          out msg
        );
        result.timeconsuming = result.GetHS();
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取列表信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="entity">查询对象</param>
    /// <param name="pageIndex">当前第几条</param>
    /// <param name="pageSize">显示多少条记录</param>
    /// <param name="funcOrderby">排序字段</param>
    /// <param name="isAsc">是否降序</param>
    /// <param name="func">额外查询条件处理拼接</param>
    /// <param name="action">额外结果处理拼接</param>
    /// <returns></returns>
    public async Task<CommonResult> GetListBySql<T>(
      T entity,
      int pageIndex,
      int pageSize,
      Expression<Func<T, object>> funcOrderby,
      bool isAsc,
      Func<string, List<SugarParameter>> func = null,
      Action<List<T>> action = null
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        string msg = string.Empty;
        baseServiceExt.ExcuteCustom(
          db =>
          {
            List<SugarParameter> parameters = new List<SugarParameter>();
            var sql = entity.GetQueryStringAndParameter<T>(func, out parameters, out msg);
            if (string.IsNullOrEmpty(msg))
            {
              List<T> list = new List<T>();
              long tottal = 0;
              var table = TableAtributeUtil.GetTable<T>();
              var querysql = $"select * from {table} {sql}";
              if (isAsc)
              {
                list = db
                  .Ado.SqlQuery<T>(querysql, parameters)
                  .AsQueryable<T>()
                  .OrderBy(funcOrderby)
                  .Skip((pageIndex - 1) * pageSize)
                  .Take(pageSize)
                  .ToList();
              }
              else
              {
                list = db
                  .Ado.SqlQuery<T>(querysql, parameters)
                  .AsQueryable<T>()
                  .OrderByDescending(funcOrderby)
                  .Skip((pageIndex - 1) * pageSize)
                  .Take(pageSize)
                  .ToList();
              }
              tottal = db.Ado.SqlQuery<T>(querysql, parameters).LongCount();
              if (action != null)
              {
                action?.Invoke(list);
              }
              result.data = list;
              result.count = tottal;
            }
          },
          out msg
        );
        result.timeconsuming = result.GetHS();
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 新增修改信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="info"></param>
    /// <param name="businessType"></param>
    /// <param name="businessLogType"></param>
    /// <param name="func"></param>
    /// <param name="action"></param>
    /// <param name="resultAction"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddOrUpdate<T>(
      T info,
      BusinessType businessType,
      BusinessLogType businessLogType,
      Func<IMySqlSugarService, CommonResult> func = null,
      Action<T> action = null,
      Action<long> resultAction = null
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        string msg = string.Empty;
        info = info.GetNewInfo();
        var model = info as BaseModel<long>;
        if (model != null)
        {
          model.loginUserCode = HttpContextExtendBase.GetLoginCode();
          var LoginrName = HttpContextExtendBase.GetLoginrName();
          //if (string.Compare("超级管理员", LoginrName, true) != 0)
          //{
          //    result.code = (int)CodeResult.nolegitimate;
          //    result.msg = "没有权限！";
          //    return result;
          //}
          var busTypeName = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType);
          var type = model.Id == 0 ? "新增" + busTypeName : "修改" + busTypeName;
          var paramJSON = JsonUtil.ToJson(info);
          autofaceInstance.DoWork(
            businessType,
            model.Id == 0 ? BusinessActionType.add : BusinessActionType.update,
            paramJSON,
            type,
            businessLogType,
            (o) =>
            {
              if (func != null)
              {
                result = func.Invoke(this.mySqlSugar);
              }
              if (action != null)
                action.Invoke(info);

              long brc = 0;
              if (model.Id == 0)
              {
                model.createuser = model.loginUserCode;
                info = model as T;
                if (func == null)
                {
                  brc = this.mySqlSugar.InserBackId<T>(info, out msg);
                }
              }
              else
              {
                brc = model.Id;
                model.modifyuser = model.loginUserCode;
                model.uTime = DateTime.Now;
                info = model as T;
                this.mySqlSugar.Update<T>(info, out msg);
              }
              resultAction?.Invoke(brc);
              if (string.IsNullOrEmpty(msg))
              {
                result.code = (int)CodeResult.success;
                result.msg = string.Empty;
                result.data = null;
                result.count = 0;
              }
              result.msg = msg;
              return result;
            },
            null,
            ref result
          );
        }
        return result;
      });
    }

    /// <summary>
    /// 删除信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <param name="businessType"></param>
    /// <param name="func"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public async Task<CommonResult> Delete<T>(
      string Id,
      string loginUserCode,
      string type,
      BusinessType businessType,
      Func<IAutofaceInstance, IMySqlSugarService, string, CommonResult> func
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        loginUserCode = HttpContextExtendBase.GetLoginCode();
        var LoginrName = HttpContextExtendBase.GetLoginrName();
        if (string.IsNullOrEmpty(Id))
        {
          result.code = (int)CodeResult.fail;
          result.msg = "删除的信息编号不明确！";
          return result;
        }
        var busTypeName = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType);
        string msg = string.Empty;
        var newid = Id.Split(',');
        var table = TableAtributeUtil.GetTable<T>();
        var sql = $"select * from {table} where id in (@Id)";
        var list = this.mySqlSugar.QueryBySqlPara<Spconf>(
          sql,
          new { Id = newid.Select(int.Parse).ToArray() },
          out msg
        );
        if (string.IsNullOrEmpty(msg) && list.Count > 0)
        {
          var headers = HttpContextExtendBase.Current.Request.Headers;
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          var remoteIp =
            LogClass.GetIPAddress()
            + "|"
            + headers["X-Real-IP"].ToString()
            + "|"
            + headers["X-Forwarded-For"].ToString();
          if (string.Compare(remoteIp, "::1", true) == 0)
          {
            remoteIp = HttpContextExtendBase
              .Current.Connection.LocalIpAddress.MapToIPv4()
              ?.ToString();
          }
          if (remoteIp.Split(':').Length >= 3)
          {
            remoteIp = remoteIp.Split(':')[3];
          }
          if (!string.IsNullOrEmpty(remoteIp))
          {
            remoteIp = remoteIp.Replace("unknow", "").Replace("|", "");
          }
          var RemoteIpAddress = HttpContextExtendBase.Current.Connection.RemoteIpAddress;
          var ipaddress = string.Empty;
          var newripad = RemoteIpAddress.ToString();
          if (!string.IsNullOrEmpty(newripad))
          {
            if (string.Compare(newripad, "::1", true) != 0)
            {
              ipaddress = $"{remoteIp + "|" + RemoteIpAddress}";
            }
            else
            {
              ipaddress = remoteIp;
            }
          }
          else
          {
            ipaddress = remoteIp;
          }
          ipaddress = ipaddress.Replace("|::ffff:", "");
          Log log = new Log()
          {
            ipaddress = ipaddress,
            lmodule = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType),
            ltype = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
              BusinessActionType.delete
            ),
            lrole = LoginrName,
            luser = loginUserCode,
            lsuccess = 1,
            status = 1,
            lcontent =
              $"用户：{loginUserCode}"
              + (
                type == "-9"
                  ? "移除到回收站" + $"删数据成功，参数：{Id},删除具体信息【{JsonUtil.ToJson(list)}】"
                  : "永久" + $"删除数据成功，参数：{Id},删除具体信息【{JsonUtil.ToJson(list)}】"
              )
          };
          this.mySqlSugar.InserBackId(log, out msg);
        }
        foreach (var newId in newid)
        {
          result = func.Invoke(autofaceInstance, this.mySqlSugar, newId);
        }
        result.etTime = DateTime.Now;
        return result;
      });
    }

    /// <summary>
    /// 删除信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <param name="businessType"></param>
    /// <param name="func"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public async Task<CommonResult> Delete<T>(
      string Id,
      string loginUserCode,
      string type,
      BusinessType businessType,
      Func<IAutofaceInstance, IMySqlSugarService, T, string> func,
      Action<IMySqlSugarService, T> action = null
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var LoginrName = HttpContextExtendBase.GetLoginrName();
        if (string.IsNullOrEmpty(Id))
        {
          result.code = (int)CodeResult.fail;
          result.msg = "删除的信息编号不明确！";
          return result;
        }
        var busTypeName = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType);
        string msg = string.Empty;
        var table = TableAtributeUtil.GetTable<T>();
        var newid = Id.Split(',');
        var key = TableAtributeUtil.GetPrimaryKey<T>();
        var sql = $"select * from {table} where id in (@Id)";
        var list = this.mySqlSugar.QueryBySqlPara<Spconf>(
          sql,
          new { Id = newid.Select(int.Parse).ToArray() },
          out msg
        );
        if (string.IsNullOrEmpty(msg) && list.Count > 0)
        {
          var headers = HttpContextExtendBase.Current.Request.Headers;
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          var remoteIp =
            LogClass.GetIPAddress()
            + "|"
            + headers["X-Real-IP"].ToString()
            + "|"
            + headers["X-Forwarded-For"].ToString();
          if (string.Compare(remoteIp, "::1", true) == 0)
          {
            remoteIp = HttpContextExtendBase
              .Current.Connection.LocalIpAddress.MapToIPv4()
              ?.ToString();
          }
          if (remoteIp.Split(':').Length >= 3)
          {
            remoteIp = remoteIp.Split(':')[3];
          }
          if (!string.IsNullOrEmpty(remoteIp))
          {
            remoteIp = remoteIp.Replace("unknow", "").Replace("|", "");
          }
          var RemoteIpAddress = HttpContextExtendBase.Current.Connection.RemoteIpAddress;
          var ipaddress = string.Empty;
          var newripad = RemoteIpAddress.ToString();
          if (!string.IsNullOrEmpty(newripad))
          {
            if (string.Compare(newripad, "::1", true) != 0)
            {
              ipaddress = $"{remoteIp + "|" + RemoteIpAddress}";
            }
            else
            {
              ipaddress = remoteIp;
            }
          }
          else
          {
            ipaddress = remoteIp;
          }
          ipaddress = ipaddress.Replace("|::ffff:", "");
          Log log = new Log()
          {
            ipaddress = ipaddress,
            lmodule = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType),
            ltype = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
              BusinessActionType.delete
            ),
            luser = loginUserCode,
            lrole = LoginrName,
            lsuccess = 1,
            status = 1,
            lcontent =
              $"用户：{loginUserCode}"
              + (
                type == "-9"
                  ? "移回回收站" + $"删除数据成功，参数：{Id},删除具体信息{JsonUtil.ToJson(list)}"
                  : "永久" + $"删除数据成功，参数：{Id},删除具体信息{JsonUtil.ToJson(list)}"
              )
          };
          this.mySqlSugar.InserBackId(log, out msg);
        }
        foreach (var newId in newid)
        {
          var info = default(T);
          info = this.mySqlSugar.FindById<T>(newId.GetIntValue(), out msg);
          var deletedata = string.Empty;
          string delmsg = string.Empty;
          if (func != null && info != null)
          {
            delmsg = func.Invoke(autofaceInstance, this.mySqlSugar, info);
            deletedata = type + "Delete[" + delmsg + "]" + busTypeName;
          }
          if (delmsg.Contains("失败"))
          {
            result.code = (int)CodeResult.fail;
            result.msg = delmsg;
            return result;
          }
          autofaceInstance.DoWork(
            businessType,
            BusinessActionType.delete,
            null,
            deletedata,
            BusinessLogType.writeLogToDataBase,
            (o) =>
            {
              if (info != null)
              {
                var newinfo = info as BaseModel<long>;
                if (newinfo.Id > 0)
                {
                  string sql = string.Empty;
                  var tableName = TableAtributeUtil.GetTable<T>();
                  if (string.Compare(type, "-9", true) == 0)
                  {
                    sql = $"update {tableName} set status=-9 where Id='{newinfo.Id}';";
                  }
                  else
                  {
                    sql = $"delete from {tableName} where Id='{newinfo.Id}';";
                    action?.Invoke(this.mySqlSugar, info as T);
                  }
                  this.mySqlSugar.ExecuteSql(sql, out var msg, null);
                  if (string.IsNullOrEmpty(msg))
                  {
                    result.code = (int)CodeResult.success;
                  }
                }
                else
                {
                  msg = "[" + Id + "]" + busTypeName + "信息不存在";
                }
              }
              result.msg = msg;
              return result;
            },
            null,
            ref result
          );
        }
        return result;
      });
    }

    /// <summary>
    /// 还原删除的信息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="businessType"></param>
    /// <param name="func"></param>
    /// <param name="action"></param>
    /// <param name="upstatus"></param>
    /// <returns></returns>
    public async Task<CommonResult> Reduction<T>(
      string Id,
      string loginUserCode,
      BusinessType businessType,
      Func<IAutofaceInstance, IMySqlSugarService, T, string> func,
      Action<IMySqlSugarService, T> action = null,
      string upstatus = ""
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var LoginrName = HttpContextExtendBase.GetLoginrName();
        if (string.IsNullOrEmpty(Id))
        {
          result.msg = ImplementResult.ParameterException.GetRemark();
          return result;
        }
        var busTypeName = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType);
        string msg = string.Empty;
        var newid = Id.Split(',');
        foreach (var newId in newid)
        {
          var info = default(T);
          info = this.mySqlSugar.FindById<T>(newId.GetIntValue(), out msg);
          var deletedata = string.Empty;
          var status = "status=1";
          if (func != null)
          {
            deletedata =
              "还原[" + func.Invoke(autofaceInstance, this.mySqlSugar, info) + "]" + busTypeName;
          }

          if (!string.IsNullOrEmpty(upstatus))
          {
            status = upstatus;
          }
          autofaceInstance.DoWork(
            businessType,
            BusinessActionType.reduction,
            null,
            deletedata,
            BusinessLogType.writeLogToDataBase,
            (o) =>
            {
              var newinfo = info as BaseModel<long>;
              if (newinfo.Id > 0)
              {
                string sql = string.Empty;
                var tableName = TableAtributeUtil.GetTable<T>();
                sql = $"update {tableName} set  {status} where Id='{newinfo.Id}';";
                this.mySqlSugar.ExecuteSql(sql, out msg, null);
              }
              else
              {
                msg = "[" + Id + "]" + busTypeName + ImplementResult.DataNotExist.GetRemark();
              }
              result.msg = msg;
              return result;
            },
            null,
            ref result
          );
        }
        return result;
      });
    }

    /// <summary>
    /// 执行业务SQL操作
    /// </summary>
    /// <param name="businessType"></param>
    /// <param name="businessActionType"></param>
    /// <param name="businessLogType"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="paramJSON"></param>
    /// <param name="type"></param>
    /// <param name="func"></param>
    /// <returns></returns>
    public async Task<CommonResult> DoAction(
      BusinessType businessType,
      BusinessActionType businessActionType,
      BusinessLogType businessLogType,
      string loginUserCode,
      string paramJSON,
      string type,
      Func<IMySqlSugarService, CommonResult> func
    )
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        //var LoginrName = HttpContextExtendBase.GetLoginrName();
        //if (string.Compare("超级管理员", LoginrName, true) != 0)
        //{
        //    result.code = (int)CodeResult.nolegitimate;
        //    result.msg = "没有权限！";
        //    return result;
        //}
        autofaceInstance.DoWork(
          businessType,
          businessActionType,
          paramJSON,
          type,
          businessLogType,
          (o) =>
          {
            result = func.Invoke(this.mySqlSugar);
            return result;
          },
          null,
          ref result
        );
        return result;
      });
    }

    /// <summary>
    /// 批量审核
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="businessType"></param>
    /// <param name="businessActionType"></param>
    /// <param name="businessLogType"></param>
    /// <param name="data"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="saveUser"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public async Task<CommonResult> ConfirmAll<T>(
      BusinessType businessType,
      BusinessActionType businessActionType,
      BusinessLogType businessLogType,
      string data,
      string loginUserCode,
      string saveUser = ""
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        loginUserCode = HttpContextExtendBase.GetLoginCode();
        autofaceInstance.DoWork(
          businessType,
          businessActionType,
          data,
          "批量审核",
          businessLogType,
          (o) =>
          {
            if (string.IsNullOrEmpty(data))
            {
              result.msg = "参数不正确";
              return result;
            }
            var LoginrName = HttpContextExtendBase.GetLoginrName();
            //if (string.Compare("超级管理员", LoginrName, true) != 0)
            //{
            //    result.code = (int)CodeResult.nolegitimate;
            //    result.msg = "没有权限！";
            //    return result;
            //}
            var tableName = TableAtributeUtil.GetTable<T>();
            string msg = string.Empty;
            StringBuilder sb = new StringBuilder();
            var shdata = JsonUtil.UnRendResults<ConfirmModel>(data);
            foreach (var item in shdata)
            {
              var sql = $"update {tableName} set status=@status where Id=@Id";
              List<SugarParameter> param = new List<SugarParameter>();
              param.Add(new SugarParameter("@status", item.status));
              param.Add(new SugarParameter("@Id", item.Id));
              if (!string.IsNullOrEmpty(saveUser))
              {
                sql = $"update {tableName} set status=@status  {saveUser}=@saveUser where Id=@Id";
                param.Add(new SugarParameter("@saveUser", loginUserCode));
              }
              this.mySqlSugar.ExecuteSql(sql, param, out msg);
              if (!string.IsNullOrEmpty(msg))
                sb.Append(msg);
            }
            if (string.IsNullOrEmpty(sb.ToString()))
            {
              Task.Factory.StartNew(() =>
              {
                var table = TableAtributeUtil.GetTable<T>();
                var shdata = JsonUtil.UnRendResults<ConfirmModel>(data);
                var ids = shdata.Select(o => o.Id.GetIntValue()).ToArray();
                var sql = $"select * from {table} where id in (@Id)";
                List<SugarParameter> parameters = new List<SugarParameter>();
                parameters.Add(new SugarParameter("@Id", ids));
                var list = this.mySqlSugar.QueryBySqlPara<Spconf>(sql, parameters, out var msg);
                if (string.IsNullOrEmpty(msg) && list.Count > 0)
                {
                  Log log = new Log()
                  {
                    lmodule = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
                      businessType
                    ),
                    ltype = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
                      BusinessActionType.check
                    ),
                    luser = loginUserCode,
                    lsuccess = 1,
                    status = 1,
                    lcontent = $"用户：{loginUserCode}审核数据成功，参数：{data},审核具体信息{JsonUtil.ToJson(list)}"
                  };
                  this.mySqlSugar.InserBackId(log, out msg);
                }
              });
            }
            result.msg = sb.ToString();
            return result;
          },
          null,
          ref result
        );
        return result;
      });
    }

    /// <summary>
    /// 审核数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="businessType"></param>
    /// <param name="businessActionType"></param>
    /// <param name="businessLogType"></param>
    /// <param name="id"></param>
    /// <param name="type"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="saveUser"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public async Task<CommonResult> Confirm<T>(
      BusinessType businessType,
      BusinessActionType businessActionType,
      BusinessLogType businessLogType,
      string id,
      int type,
      string loginUserCode,
      string saveUser = ""
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var LoginrName = HttpContextExtendBase.GetLoginrName();
        //if (string.Compare("超级管理员", LoginrName, true) == 0)
        //{
        //    result.code = (int)CodeResult.nolegitimate;
        //    result.msg = "没有权限！";
        //    return result;
        //}
        autofaceInstance.DoWork(
          businessType,
          businessActionType,
          id + "|" + type,
          "审核数据",
          businessLogType,
          (o) =>
          {
            var tableName = TableAtributeUtil.GetTable<T>();
            var sql = $"update {tableName} set status=@status where Id=@Id;";
            List<SugarParameter> parameters = new List<SugarParameter>();
            parameters.Add(new SugarParameter("@status", type));
            parameters.Add(new SugarParameter("@Id", id));
            if (!string.IsNullOrEmpty(saveUser))
            {
              sql = $"update {tableName} set status=@status,{saveUser}=@saveuser where Id=@Id;";
              parameters.Add(new SugarParameter("@saveuser", loginUserCode));
            }
            string msg = string.Empty;
            this.mySqlSugar.ExecuteSql(sql, parameters, out msg);
            if (string.IsNullOrEmpty(msg))
            {
              var table = TableAtributeUtil.GetTable<T>();
              sql = $"select * from {table} where id=@id;";
              var list = this.mySqlSugar.QueryBySqlPara<T>(sql, new { id = id }, out msg);
              if (string.IsNullOrEmpty(msg) && list.Count > 0)
              {
                Log log = new Log()
                {
                  lmodule = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(businessType),
                  ltype = BusinessAttributeUtil.GetAttributeName<BusinessAttribute>(
                    BusinessActionType.check
                  ),
                  luser = loginUserCode,
                  lsuccess = 1,
                  status = 1,
                  lcontent =
                    $"用户：{loginUserCode}审核数据成功，参数：{id}-{type},审核具体信息{JsonUtil.ToJson(list)}"
                };
                this.mySqlSugar.InserBackId(log, out msg);
              }
            }
            result.msg = msg;
            return result;
          },
          null,
          ref result
        );
        return result;
      });
    }

    /// <summary>
    /// 检查数据是否存在
    /// </summary>
    /// <param name="businessType"></param>
    /// <param name="businessLogType"></param>
    /// <param name="sql"></param>
    /// <param name="paramdata"></param>
    /// <param name="checkname"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckDataExists<T>(
      BusinessType businessType,
      BusinessLogType businessLogType,
      Expression<Func<T, bool>> expression,
      string checkname,
      string Id
    )
      where T : class, new()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        string msg = string.Empty;
        var list = this.mySqlSugar.QueryByExpression<T>(expression, out msg);
        if (string.IsNullOrEmpty(msg) && list != null)
        {
          if (string.IsNullOrEmpty(Id) || string.Compare(Id, "null", true) == 0 || string.Compare(Id, "0", true) == 0)
              {
            if (list.Count > 0)
            {
              result.msg = ImplementResult.DataExist.GetRemark();
            }
          }
          else
          {
            if (list.Count > 1)
            {
              result.msg = ImplementResult.DataExist.GetRemark();
            }
            else
            {
              if (list.Count > 0)
              {
                var haveId = list.FirstOrDefault().GetId<T>().ToString();
                if (Id.GetIntValue() > 0)
                {
                  if (string.Compare(haveId, Id, true) != 0)
                  {
                    result.msg = ImplementResult.DataExist.GetRemark();
                  }
                }
              }
            }
          }
        }
        else
        {
          result.msg = ImplementResult.DataExist.GetRemark();
        }
        return result;
      });
    }

    /// <summary>
    /// 根据城市名称获取城市对应代码
    /// </summary>
    /// <param name="cname"></param>
    /// <returns></returns>
    public City GetCityInfo(string cname)
    {
      return this.cities.Where(o => o.class_name.Contains(cname))?.FirstOrDefault();
    }

    /// <summary>
    /// 上传头像
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="files"></param>
    /// <param name="name"></param>
    /// <param name="filename"></param>
    /// <param name="model"></param>
    /// <param name="path"></param>
    /// <param name="businessType"></param>
    /// <returns></returns>
    public async Task<CommonResult> UploadFile<T>(
      IFormFileCollection files,
      string name,
      string filename,
      UploadYPhoto model,
      string path,
      BusinessType businessType
    )
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        model.logincode = HttpContextExtendBase.GetLoginCode();
        var LoginrName = HttpContextExtendBase.GetLoginrName();
        //if (string.Compare("超级管理员", LoginrName, true) != 0)
        //{
        //    result.code = (int)CodeResult.nolegitimate;
        //    result.msg = "没有权限！";
        //    return result;
        //}
        autofaceInstance.DoWork(
          businessType,
          BusinessActionType.uploadfile,
          model.logincode,
          name,
          BusinessLogType.writeLogToDataBase,
          (o) =>
          {
            var userTable = TableAtributeUtil.GetTable<T>();
            string msg = string.Empty;
            if (string.Compare(model.uid, "0", true) != 0)
            {
              var sqlb = $"select file from {userTable} where Id={model.uid};";
              var dt = this.mySqlSugar.GetDataTable(sqlb, out msg, null);
              if (dt.Rows.Count > 0)
              {
                var uploadyhead = dt.Rows[0][filename].ToString();
                if (!string.IsNullOrEmpty(uploadyhead))
                {
                  FileUtil.DelFile(
                    path + "/Files/Uploads/" + DateTime.Now.ToString("yyyyMMdd") + "/" + uploadyhead
                  );
                }
              }
            }
            var preff = "/Files/Uploads/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            long size = 0;
            string FileName = string.Empty;
            foreach (var file in files)
            {
              var fileext = Path.GetExtension(file.FileName);
              if (fileext.Contains(".php") || fileext.Contains(".asp") || fileext.Contains(".jsp"))
              {
                throw new Exception("当前文件不在允许上传范围内已拦截！");
              }
              var extname = Path.GetExtension(file.FileName);
              if (string.IsNullOrEmpty(extname))
              {
                result.code = (int)CodeResult.fail;
                result.msg = $"本次上传未成功：当前上传文件{file.FileName}是未知后缀名文件，请先指定具体后缀名！";
                break;
              }
              FileName = file.FileName;
              var fileDir = Path.Combine(path + "\\" + preff);
              if (!Directory.Exists(fileDir))
              {
                Directory.CreateDirectory(fileDir);
              }
              string filePath = fileDir + $@"\{FileName}";
              size += file.Length;
              filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
              using (FileStream fs = System.IO.File.Create(filePath))
              {
                file.CopyTo(fs);
                fs.Flush();
              }
              if (ImageUtil.IsImage(filePath)) //如果是图片进行压缩
              {
                ImageUtil.Compressc(filePath, filePath);
              }
            }
            if (string.Compare(model.uid, "0", true) != 0)
            {
              var sql = $"update {userTable} set file='{FileName}' where Id='{model.uid}';";
              this.mySqlSugar.ExecuteSql(sql, out msg, null);
            }
            result.code = (int)CodeResult.success;
            result.data = preff + FileName;
            return result;
          },
          null,
          ref result
        );
        return result;
      });
    }

    /// <summary>
    /// 附件上传
    /// </summary>
    /// <param name="files"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public async Task<CommonResult> UploadFile(IFormFileCollection files, string path)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        path = path + "\\Files\\Uploads\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
        path = path.Replace("\\", "/"); // Linux系统部署路径需要改成这样
        if (!FileUtil.ExistsDir(path))
          FileUtil.CreateDirectory(path);

        foreach (var formFile in files)
        {
          var fileext = Path.GetExtension(formFile.FileName);
          if (fileext.Contains(".php") || fileext.Contains(".asp") || fileext.Contains(".jsp"))
          {
            throw new Exception("当前文件不在允许上传范围内已拦截！");
          }
          if (formFile.Length > 0)
          {
            var extname = Path.GetExtension(formFile.FileName);
            if (string.IsNullOrEmpty(extname))
            {
              result.msg = $"本次上传未成功：当前上传文件{formFile.FileName}是未知后缀名文件，请先指定具体后缀名！";
              break;
            }
            var filePath = path + formFile.FileName;
            filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
              formFile.CopyTo(stream);
            }
            if (ImageUtil.IsImage(filePath)) //如果是图片进行压缩
            {
              ImageUtil.Compressc(filePath, filePath);
            }
            result.data =
              "//Files//Uploads//" + DateTime.Now.ToString("yyyyMMdd") + "//" + formFile.FileName;
          }
        }
        result.etTime = DateTime.Now;
        return result;
      });
    }

    /// <summary>
    /// 附件上传
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="files"></param>
    /// <param name="path"></param>
    /// <param name="filename"></param>
    /// <param name="id"></param>
    /// <param name="filecount"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<CommonResult> UploadFile<T>(
      IFormFileCollection files,
      string path,
      string filename,
      string id,
      string filecount = "1"
    )
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        path = path + "\\Files\\Uploads\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
        path = path.Replace("\\", "/"); // Linux系统部署路径需要改成这样
        if (!FileUtil.ExistsDir(path))
          FileUtil.CreateDirectory(path);

        if (string.IsNullOrEmpty(filecount))
        {
          filecount = "1";
        }
        var loginUserCode = HttpContextExtendBase.GetLoginCode();
        ;
        var table = TableAtributeUtil.GetTable<T>();
        var success = 0;
        var error = 0;
        List<string> ifs = new List<string>();
        var sql = string.Empty;
        var msg = string.Empty;
        long filesize = 0;
        foreach (var formFile in files)
        {
          var fileext = Path.GetExtension(formFile.FileName.ReplaceStrChar());
          if (fileext.Contains(".php") || fileext.Contains(".asp") || fileext.Contains(".jsp"))
          {
            throw new Exception("当前文件不在允许上传范围内已拦截！");
          }
          try
          {
            if (formFile.Length > 0)
            {
              var extname = Path.GetExtension(formFile.FileName.ReplaceStrChar());
              if (string.IsNullOrEmpty(extname))
              {
                result.msg =
                  $"本次上传未成功：当前上传文件【{formFile.FileName.ReplaceStrChar()}】是未知后缀名文件，请先指定具体后缀名！";
                break;
              }
              var newfilename = formFile.FileName.ReplaceStrChar().ReplaceStrChar();
              if (!string.IsNullOrEmpty(id))
              {
                if (filecount.GetIntValue() > 1)
                {
                  sql = $"select {filename} from {table} where id={id};";
                  var havedt = this.mySqlSugar.GetDataTable(sql, null, out msg);
                  if (string.IsNullOrEmpty(msg) && havedt != null && havedt.Rows.Count > 0)
                  {
                    var filevalue = havedt.Rows[0][filename].ToString();
                    if (!string.IsNullOrEmpty(filevalue))
                    {
                      foreach (var item in filevalue.Split(','))
                      {
                        ifs.Add(item);
                      }
                      var filevaluenew =
                        filevalue
                        + ","
                        + $"//Files//Uploads//{DateTime.Now.ToString("yyyyMMdd")}//{newfilename}";
                      sql = $"update {table} set {filename}='{filevaluenew}' where Id={id};";
                    }
                    else
                    {
                      sql =
                        $"update {table} set {filename}='//Files//Uploads//{DateTime.Now.ToString("yyyyMMdd")}//{newfilename}' where Id={id};";
                    }
                    this.mySqlSugar.ExecuteSql(sql, null, out var msgb);
                  }
                }
                else
                {
                  sql =
                    $"update {table} set {filename}='//Files//Uploads//{DateTime.Now.ToString("yyyyMMdd")}//{newfilename}' where Id={id};";
                  this.mySqlSugar.ExecuteSql(sql, null, out var msgb);
                }
              }
              var filePath = path + newfilename;
              filePath = filePath.Replace("\\", "/"); // Linux系统部署路径需要改成这样
              using (var stream = new FileStream(filePath, FileMode.Create))
              {
                formFile.CopyTo(stream);
              }
              filesize = formFile.Length;
              success++;
              if (ImageUtil.IsImage(filePath)) //如果是图片进行压缩
              {
                ImageUtil.Compressc(filePath, filePath);
              }
              ifs.Add(
                "//Files//Uploads//" + DateTime.Now.ToString("yyyyMMdd") + "//" + newfilename
              );
            }
          }
          catch (Exception ex)
          {
            error++;
          }
        }
        if (ifs.Count > 0)
        {
          result.data = string.Join(",", ifs) + "|" + success + "|" + error + "|" + filesize;
        }
        else
        {
          result.data = "|" + success + "|" + error;
        }
        return result;
      });
    }
  }
}
